package com.wh.order.util;

import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import cn.afterturn.easypoi.handler.inter.IExcelExportServer;
import com.wh.order.pojo.OrderProducid;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;

import cn.afterturn.easypoi.handler.impl.ExcelDataHandlerDefaultImpl;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Objects;

public class ImageUrlHandler extends ExcelDataHandlerDefaultImpl {

    @Override
    public Object exportHandler(Object obj, String name, Object value) {
        // If the column is "产品图片" and the value is a string (image URL)
        if ("picture".equals(name) && value instanceof String) {
            String imageUrl = (String) value;
            try {
                // Convert image URL to byte array
                byte[] imageBytes = getImageBytes(imageUrl);

                // Return byte array
                return imageBytes;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.exportHandler(obj, name, value);
    }

    @Override
    public Object importHandler(Object obj, String name, Object value) {
        return super.importHandler(obj, name, value);
    }

    private byte[] getImageBytes(String imageUrl) throws IOException {
        // Read image from URL and convert to byte array
        BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, "jpg", outputStream);
        return outputStream.toByteArray();
    }
}